/*
 * librolgps, part of the RolGPS Proyect
 *
 *   
 * Copyright (C) Pablo Alejandro Costesich <rhfixer@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
package dataTypes;

import databaseHandler.Database;
import deployers.sqlite.Deployer;
import deployers.sqlite.Field;
import deployers.sqlite.Table;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author xeph
 */
public class ObjectSource extends Database {

    public ObjectSource(File database) {
        this.setDatabaseFile(database);
    }

    public InteractiveObject[] search(InteractiveObject model) {
        InteractiveObject[] resultado = new InteractiveObject[0];
        try {
            //prepare the select

            StringBuffer sqlquery = new StringBuffer();
                    
            sqlquery.append(
                    "SELECT interactiveobjects.id, " +
                    "interactiveobjects.name, " +
                    "interactiveobjects.uid, " +
                    "interactiveobjects.x, " +
                    "interactiveobjects.y, " +
                    "interactiveobjects.z " +
                    " FROM interactiveobjects WHERE 1=1");
            if (!model.getName().equals("")) {
                sqlquery.append(" AND interactiveobjects.name like '%" + model.getName() + "%'");
            }
            if (!model.getId().equals("")) {
                sqlquery.append(" AND interactiveobjects.id = " + model.getId() + "");
            }
            if (!model.getUserId().equals("")) {
                sqlquery.append(" AND interactiveobjects.uid like '" + model.getUserId() + "'");
            }
            if (!model.getX().equals("")) {
                sqlquery.append(" AND interactiveobjects.x = '" + model.getX() + "'");
            }
            if (!model.getY().equals("")) {
                sqlquery.append(" AND interactiveobjects.y = '" + model.getY() + "'");
            }
            if (!model.getZ().equals("")) {
                sqlquery.append(" AND interactiveobjects.z = '" + model.getZ() + "'");
            }

            sqlquery.append(";");
            //System.out.println(sqlquery);
            Object[][] result = this.executeStatement(sqlquery.toString()); //este search corresponde a database, NO a ObjectSource.
            //como Object es una matriz de dos dimensiones, se maneja primero por fila y luego por columna.

            //creo los resultados.
            InteractiveObject[] searchResult = new InteractiveObject[result.length];
            for (int iterator = 0; iterator < searchResult.length; iterator++) {
                searchResult[iterator] = new InteractiveObject();
                searchResult[iterator].setId(result[iterator][0].toString());
                searchResult[iterator].setName(result[iterator][1].toString());
                searchResult[iterator].setUserId(result[iterator][2].toString());
                searchResult[iterator].setX(result[iterator][3].toString());
                searchResult[iterator].setY(result[iterator][4].toString());
                searchResult[iterator].setZ(result[iterator][5].toString());
            }
//            arraySize=searchResult.length;
            resultado = searchResult;

        } catch (SQLException ex) {
            //Logger.getLogger(ObjectSource.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println("BAD SQL QUERY.");
        }


        return resultado;
    }

    public void insert(InteractiveObject model) {
        try {
            StringBuffer sqlquery = new StringBuffer();
            sqlquery.append("INSERT INTO interactiveobjects (id, name, uid, x, y, z) VALUES(null , '" + 
                    model.getName() + "', '" + 
                    model.getUserId() + "', '" + 
                    model.getX() + "' , '" + 
                    model.getY() + "' , '" + 
                    model.getZ() + "' );");
            Object[][] resultado = this.executeStatement(sqlquery.toString());
            if (resultado[0][0].equals("0")) {

            }
        } catch (SQLException ex) {
            this.deploy();
            this.insert(model);
        }
    }

    //este delete NO deberia usarse. Es mejor incluir un objeto modelo, deberia ser privado
    public void delete(InteractiveObject model) {
        try {
            StringBuffer sqlquery = new StringBuffer();
            sqlquery.append( "DELETE FROM interactiveobjects WHERE 1=1 ");
            if (!model.getName().equals("")) {
                sqlquery.append(" AND name like '%" + model.getName() + "%'");
            }
            if (!model.getId().equals("")) {
                sqlquery.append(" AND id = " + model.getId() + "");
            }
            if (!model.getUserId().equals("")) {
                sqlquery.append(" AND uid like '" + model.getUserId() + "'");
            }
            if (!model.getX().equals("")) {
                sqlquery.append(" AND x = '" + model.getX() + "'");
            }
            if (!model.getY().equals("")) {
                sqlquery.append(" AND y = '" + model.getY() + "'");
            }
            if (!model.getZ().equals("")) {
                sqlquery.append(" AND z = '" + model.getZ() + "'");
            }
            sqlquery.append(";");
            Object[][] resultado = this.executeStatement(sqlquery.toString());
            if (resultado[0][0].equals("0")) {

            }
        } catch (SQLException ex) {
            Logger.getLogger(ObjectSource.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void update(String id, InteractiveObject model) {
        try {
            if (id.equals("")) {
                id = model.getId();
            }
            StringBuffer sqlquery = new StringBuffer();
            sqlquery.append("UPDATE interactiveobjects SET" +
                    " name = '" + model.getName() + "', " +
                    " uid = '" + model.getUserId() + "', " +
                    " x = '" + model.getX() + "', " +
                    " y = '" + model.getY() + "', " +
                    " z = '" + model.getZ() + "'");

            sqlquery.append(" WHERE id=" + id + ";");

            Object[][] resultado = this.executeStatement(sqlquery.toString());
            if (resultado[0][0].equals("0")) {
            }
        } catch (SQLException ex) {
            //Logger.getLogger(ObjectSource.class.getName()).log(Level.SEVERE, null, ex);
            this.deploy();
            this.update(id, model);
        }
    }

    public void deploy() {
        try {
            Deployer deployer = new Deployer(this.getCurrentDatabaseFile());
            Table iobjects = new Table("interactiveobjects");

            Field id = new Field("id");
            id.addType(Field.IDFIELD);
            iobjects.addField(id);

            Field nombre = new Field("name");
            nombre.addType(Field.STRING);
            iobjects.addField(nombre);

            Field uid = new Field("uid");
            uid.addType(Field.INTEGER);
            iobjects.addField(uid);

            Field ex = new Field("x");
            ex.addType(Field.INTEGER);
            iobjects.addField(ex);

            Field why = new Field("y");
            why.addType(Field.INTEGER);
            iobjects.addField(why);

            Field zed = new Field("z");
            zed.addType(Field.INTEGER);
            iobjects.addField(zed);

            deployer.addTable(iobjects);

            deployer.deploy();
        } catch (IOException ex) {
            Logger.getLogger(ObjectSource.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void remove() {

    }
}


